import time

import requests
import pyaudio
import asyncio
import logging

from fastapi import HTTPException


async def play_audio_from_stream(url, data, config, chunk_size=8192):
    start_time = time.time()
    response = requests.get(url, data=data, stream=True)
    audio_data = bytearray()
    try:
        if response.status_code == 200:
            p = pyaudio.PyAudio()
            stream = p.open(format=p.get_format_from_width(config.AUDIO_SAMP_WIDTH),
                            channels=config.AUDIO_CHANNELS,
                            rate=config.AUDIO_RATE_OUT,
                            output=True)
            for chunk in response.iter_content(chunk_size=chunk_size):
                if chunk:
                    # 播放音频流
                    # stream.write(chunk)
                    audio_data.extend(chunk)
                    await asyncio.sleep(0)
            stream.stop_stream()
            stream.close()
            p.terminate()
            end_time = time.time()
            if not audio_data:
                logging.error("音频生成失败，可能是语音合成服务出现问题或请求参数有误。")
                raise HTTPException(status_code=400, detail="音频生成失败，请检查请求参数或语音合成服务状态。")
            logging.info(f"音频生成成功，耗时 {end_time - start_time:.2f} 秒，音频数据大小 {len(audio_data)} 字节")
            return bytes(audio_data)
        else:
            error_msg = f"音频生成请求失败，状态码 {response.status_code}，原因可能是 {response.reason}"
            logging.error(error_msg)
            return error_msg
    except requests.exceptions.RequestException as e:
        logging.error(f"网络连接出现问题导致音频生成失败: {e}")
        raise HTTPException(status_code=400, detail="音频生成失败，网络连接出现问题，请检查网络设置后重试。")
    except Exception as e:
        logging.error(f"音频生成出现其他错误: {e}")
        raise HTTPException(status_code=500, detail="音频生成出现内部错误，请联系管理员。")